<template>
    <div class="flex items-center justify-center">
        <div class="w-full px-2" style="max-width:1440px;">
            <div id="movie-list" class="p-2 grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                <div class="movie" v-for="movie in movies.results" :key="movie.id">
                    <a :href="'/movie/' + movie.id">
                        <div class="relative">
                            <div v-if="movie.image_url" class="cover">
                                <img :src="movie.image_url" referrerPolicy="no-referrer" alt=""
                                    class="rounded h-full w-full">
                            </div>
                            <div v-else>
                                <img src="@/assets/images/nopicture.jpg" alt="" class="rounded h-full w-full">
                            </div>
                            <div v-if="movie.is_top" class="rounded absolute top-0 bg-purple-600 px-1 text-sm">
                                置顶
                            </div>
                            <div v-if="movie.quality === 1"
                                class="rounded absolute bottom-0 right-0 bg-blue-500 px-1 text-sm ">
                                720p
                            </div>
                            <div v-else-if="movie.quality === 2"
                                class="rounded absolute bottom-0 right-0 bg-blue-500 px-1 text-sm ">
                                1080p
                            </div>
                            <div v-else-if="movie.quality === 3"
                                class="rounded absolute bottom-0 right-0 bg-blue-500 px-1 text-sm ">
                                4k
                            </div>
                        </div>
                        <p> {{ movie.movie_name }}({{ movie.release_year }})</p>
                        <p class="text-sm text-primary-200">{{ movie.language }}</p>
                    </a>
                </div>
            </div>
        </div>
        <div v-if="isLoading" class="flex items-center justify-center">
            <p>加载中...</p>
        </div>
    </div>

</template>
<script setup>
defineOptions({
    name: 'MovieListView',
})
import { computed, onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const movies = ref([])
const currentPage = ref(1)
const isLoading = ref(false)
const searchQuery = computed(() => route.query.keyword || '')
// 计算总页数
const totalPages = computed(() => movies.value.count ? Math.ceil(movies.value.count / 8) : 0)

const params = computed(() => {
    return {
        api_key: '',
        langeuage: 'zh-cn',
        page: currentPage.value,
        movie_name: searchQuery.value
    }
})

const category_id = computed(() => route.query.category_id || '')
const region = computed(() => route.query.region || '')
if (category_id.value) {
    params.value.category_id = category_id.value
}
if (region.value) {
    params.value.region = region.value
}

const fetchMovies = (append = false) => {
    isLoading.value = true;
    // 构造带查询参数的URL
    const url = new URL(import.meta.env.VITE_API_URL + '/movie/')
    try {
        axios.get(url.toString(), {
            params: params.value
        })
            .then((res) => {
                if (append) {
                    movies.value.results.push(...res.data.results)
                } else {
                    movies.value = res.data
                }
                isLoading.value = false;
            })
            .catch((err) => {
                console.log(err)
                isLoading.value = false;
            })


    } catch (err) {
        console.log(err)
    }
}
const searchMovies = (query, append = false) => {
    const url = new URL(import.meta.env.VITE_API_URL + '/movie/')
    isLoading.value = true;
    try {
        const res = axios.get(url.toString(), {
            params: params.value
        })
            .then((res) => {
                if (append) {
                    movies.value.results.push(...res.data.results)
                } else {
                    movies.value = res.data
                }
                isLoading.value = false;
            })
            .catch((err) => {
                console.log(err)
                isLoading.value = false;
            })
    } catch (err) {
        console.log(err)
    }
}
const handleScroll = () => {
    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
    if (scrollTop + clientHeight >= scrollHeight - 10 && !isLoading.value && currentPage.value < totalPages.value) {
        currentPage.value += 1;
        if (searchQuery.value) {
            searchMovies(searchQuery.value, true)
        } else {
            fetchMovies(true)
        }
    }
}
onMounted(() => {
    if (searchQuery.value) {
        searchMovies(searchQuery.value)
    } else {
        fetchMovies()
    }
    window.addEventListener('scroll', handleScroll)
})
// 监听路由变化
watch(route, (to, from) => {
    fetchMovies()
})

</script>
